package com.sjft.cloud.commons.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sjft.cloud.commons.security.properties.SecurityUrlProperties;
import com.sjft.cloud.commons.security.rest.RestAuthExceptionEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;


/**
 * 资源服务配置
 *
 * @author Jin
 */
@SuppressWarnings("all")
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableResourceServer
@EnableConfigurationProperties(SecurityUrlProperties.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private SecurityUrlProperties permitUrlProperties;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisTokenStore redisTokenStore;
    @Autowired
    private OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint;
    @Autowired
    private OAuth2AccessDeniedHandler restOAuth2AccessDeniedHandler;
    @Autowired
    private RestAuthExceptionEntryPoint restAuthExceptionEntryPoint;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .exceptionHandling()
                .authenticationEntryPoint(restAuthExceptionEntryPoint)
                .and()
                .headers()
                .frameOptions()
                .disable()
                .and()
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers(permitUrlProperties.getExcludePath())
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.stateless(true);
        resources.tokenStore(redisTokenStore);
        resources.authenticationEntryPoint(oAuth2AuthenticationEntryPoint);
        resources.accessDeniedHandler(restOAuth2AccessDeniedHandler);
    }

}
